package com.whjk.system.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whjk.system.biz.mapper.WhjkZhxmInfoMapper;
import com.whjk.system.biz.service.WhjkZhxmInfoService;
import com.whjk.system.biz.service.WhjkZhxmService;
import com.whjk.system.data.dto.WhjkZhxmXmDto;
import com.whjk.system.data.entity.WhjkXm;
import com.whjk.system.data.entity.WhjkZhxm;
import com.whjk.system.data.entity.WhjkZhxmInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 组合项目关联表 服务实现类
 * </p>
 *
 * @author hl
 * @since 2023-06-28
 */
@Service
public class WhjkZhxmInfoServiceImpl extends ServiceImpl<WhjkZhxmInfoMapper, WhjkZhxmInfo> implements WhjkZhxmInfoService {

    @Autowired
    private WhjkZhxmService zhxmService;

    /**
     * 查询组合中子项列表
     *
     * @param whjkZhxm
     * @return
     */
    @Override
    public List<WhjkXm> xmList(WhjkZhxm whjkZhxm) {
        return this.baseMapper.xmList(whjkZhxm.getId());
    }

    /**
     * 修改，在组合中添加子项
     *
     * @param whjkZhxmXmDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void xmAdd(WhjkZhxmXmDto whjkZhxmXmDto) {
        zhxmService.updateById(whjkZhxmXmDto);
        //原来的xmids
        List<String> oldIds = this.list(new LambdaQueryWrapper<WhjkZhxmInfo>()
                .eq(WhjkZhxmInfo::getZhxmId, whjkZhxmXmDto.getId())
                .eq(WhjkZhxmInfo::getDelFlag, 0))
                .stream().map(WhjkZhxmInfo::getTjxmId).collect(Collectors.toList());
        //需要插入的ids
        List<String> addIds = whjkZhxmXmDto.getXmIds().stream().filter(i -> !oldIds.contains(i)).collect(Collectors.toList());
        //需要删除的ids
        List<String> delIds = oldIds.stream().filter(i -> !whjkZhxmXmDto.getXmIds().contains(i)).collect(Collectors.toList());
        if(!delIds.isEmpty()){
            this.update(new UpdateWrapper<WhjkZhxmInfo>()
                    .set("del_flag", "1")
                    .eq("zhxm_id", whjkZhxmXmDto.getId())
                    .in("tjxm_id", delIds)
                    .eq("del_flag", 0));
        }
        List<WhjkZhxmInfo> infoList = addIds.stream().map(i -> {
            WhjkZhxmInfo info = new WhjkZhxmInfo();
            info.setZhxmId(whjkZhxmXmDto.getId());
            info.setTjxmId(i);
            return info;
        }).collect(Collectors.toList());
        this.saveBatch(infoList);
    }
}